package org.example;

import java.util.concurrent.*;

/**
 * Copyright (c) 2023-2033 All Rights Reserved
 *
 * @date: 2023/5/8
 */
public class CallableAndFuture {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        callableTest();
        futureTest();
        futureTaskTest();
    }

    public static class TaskCallable implements Callable<Integer> {
        @Override
        public Integer call() throws InterruptedException {
            Thread.sleep(1000L);
            return 200;
        }
    }

    public static void callableTest() throws ExecutionException, InterruptedException {
        ExecutorService executorService = Executors.newCachedThreadPool();
        TaskCallable callable = new TaskCallable();
        Future<Integer> future = executorService.submit(callable);
        future.get();

        //        // 执行 callable
//        threadPoolExecutor.submit(new Callable<String>() {
//            @Override
//            public String call() {
//                System.out.println("threadPoolExecutor.submit()");
//                return "callable";
//            }
//        });
    }

    public static void futureTest() throws ExecutionException, InterruptedException {
        ExecutorService executorService = Executors.newSingleThreadExecutor();
        Future<String> future = executorService.submit(new Callable<String>() {
            @Override
            public String call() throws Exception {
                return "futureTest";
            }
        });
        future.get();
        future.cancel(false);
        future.isDone();
    }

    public static void futureTaskTest() throws ExecutionException, InterruptedException {
        FutureTask<String> futureTask = new FutureTask<>(() -> {
            return "null";
        });
        ExecutorService executorService = Executors.newFixedThreadPool(1);
        Future<?> submit = executorService.submit(futureTask);
        submit.get();
    }

}
